04. Exercise: Exceptions
Exercise: Exceptions
Create a Phone class
Task Description:
Let's get some practice handling Exceptions. First, we will create a Phone
class:
Task Feedback:
Nice work!
Create a PhoneExceptionTester
Task Description:
Next, let's create a PhoneExceptionTester
class to test how exception flow works in Java:
Task Feedback:
Nice work!
Solution
ND079 C1 L4 A04 Exception Solutions
The important point to note is that without the try
and catch
block, the program would terminate with an exception.
public class Phone {
private final String phoneType;
private final String phoneNumber;
public Phone(String phoneType, String phoneNumber) {
super();
if (phoneType == null || phoneNumber == null) {
throw new IllegalArgumentException("The type and number cannot be null");
}
this.phoneType = phoneType;
this.phoneNumber = phoneNumber;
}
public String getPhoneType() {
return phoneType;
}
public String getPhoneNumber() {
return phoneNumber;
}
@Override
public String toString() {
return phoneType + " " + phoneNumber;
}
}
public class PhoneExceptionTester {
public static void main(String[] args) {
String[] numbers = new String[] { "123-4567", null, "234-4567", "345-5678" };
for (int i = 0; i < numbers.length; i++) {
try {
System.out.println(new Phone("iPhone", numbers[i]));
} catch (IllegalArgumentException ex) {
System.out.println(ex.getLocalizedMessage());
}
}
for (int i = 0; i < numbers.length; i++) {
System.out.println(new Phone("iPhone", numbers[i]));
}
}
}
Remember:
- You can create and throw your own exceptions by extending the Exception classes
- There are two types of exceptions in Java: Checked and unchecked. Checked exceptions will get caught at compile time and will not allow the code to build until they are either in a
catch
block or thrown. Unchecked (or runtime) exceptions are not checked by the compiler.